package com.sinhvien.model;

import java.util.ArrayList;
import java.util.List;
import com.sinhvien.vo.contact;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by THAI NHAN on 5/28/13.
 */

public class DBHander extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION =1;
    public static final String DATABASE_NAME ="contactsManager";
    public static final String TABLE_NAME= "contacts";

    // cac cot
    public static final String KEY_ID ="_id";
    public static final String KEY_NAME= "name";
    public static final String KEY_PHONE= "phone";

    public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                                            + KEY_ID + " INTERGER PRIMARY KEY,"
                                            + KEY_NAME + " TEXT,"
                                            + KEY_PHONE + " TEXT)";

    public DBHander(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i2) {
        db.execSQL("DROP TABLE IF EXIST" + TABLE_NAME);
        onCreate(db);
    }



    public void addNewContact(contact  contact){
        SQLiteDatabase db= this.getWritableDatabase();
        ContentValues value =new ContentValues();

        value.put(KEY_ID,contact.id);
        value.put(KEY_NAME,contact.name);
        value.put(KEY_PHONE,contact.phone);
        db.insert(TABLE_NAME,null,value);
        db.close();

    }

    public contact getContact(int id){
        SQLiteDatabase db= this.getReadableDatabase();
        Cursor c= db.query(TABLE_NAME, new String[]{KEY_ID,KEY_NAME,KEY_PHONE},KEY_ID + "=?",
                new String[] {String.valueOf(id)},null,null,null);
        if(c !=null){
            c.moveToFirst();
            return  new contact(Integer.parseInt(c.getString(0)), c.getString(1), c.getString(2));

        }
        return null;

    }

    public List<contact> getAllContact(){
        List<contact> list = new ArrayList<contact>();
        SQLiteDatabase db= this.getReadableDatabase();

        String query = "SELECT * FROM "+ TABLE_NAME;

        Cursor cur= db.rawQuery(query,null);
        if(cur !=null){
            cur.moveToFirst();
            do {
                contact con = new contact(Integer.parseInt(cur.getString(0)), cur.getString(1), cur.getString(2));
                list.add(con);
            }while (cur.moveToNext());
            db.close();
            return list;
        }
        db.close();
        return null;
    }
}
